<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once '/application/libraries/PHPExcel.php';
class Adminapi extends CI_Controller {

	public function __construct(){
		parent::__construct();
		$this->load->model('Agent_m');
		$this->load->model('Admin_m');
		$this->load->model('Adminlog_m');
		$this->load->model('Config_m');
		$this->load->model('Device_m');
		$this->load->model('Settlementlog_m');
		$this->load->model('Commission_m');
		$this->load->library('api/adminapi_service');
	}




	public function admin_api(){
    	switch ($_SERVER["REQUEST_METHOD"]) {
			case 'GET':
				//总后台登录
				
				# code...
				break;				
			case 'POST':
				# code...
				break;
			case 'PUT':
				# code...
				break;
			case 'DELETE':
				# code...
				break;
			default:
				# code...
				break;
		}
	}



	//每月月初代理结算上月金额
	public function doSettlement(){
		//查询上个月全部未结算分佣记录
		$firstday=date('Y-m-d', strtotime(date('Y-m-01') . ' -1 month'));
		$begin=strtotime(date("$firstday 00:00:00"));
		$lastday=date('Y-m-01');
		$stop=strtotime(date("$lastday 00:00:00"));
		$sql="select * from mifi_commission where addtime2 >= $begin and addtime2 < $stop and settlement = 0 ";
		$settlementdate=date('Ym', strtotime(date('Y-m') . ' -1 month'));
		$query = $this->db->query($sql);
		$data=$query->result_array();
		//循环累计每个代理总金额 每执行一条修改一条记录的结算状态
		$result=array();
		if($data){
			foreach ($data as $key => $value) {
				@$result[$value['agent_user_id']]+=$value['money'];
				$this->Commission_m->update(array('id'=>$value['id']),array('settlement'=>1,'settlement_time'=>date('Y-m-d H:i:s')));
			}
		}
		if($result){
			foreach ($result as $key => $value) {
				$this->Settlementlog_m->insert(array('agent_id'=>$key,'money'=>$value,'addtime'=>date('Y-m-d H:i:s'),'settlementdate'=>$settlementdate));
			}
		}
		$Settlement['success'] = success('4000');  
		$Settlement['Settlement'] = $result;
		echo _echo($Settlement);
		exit;
		// $datainfo=$this->Settlementlog_m->select(array('settlementdate'=>$settlementdate));
		// if($datainfo){
		// 	foreach ($datainfo as $key => $value) {
		// 		$agentinfo=$this->Agent_m->select(array('id'=>$value['agent_id']));
		// 		$table[$key][]=$value['id'];
		// 		$table[$key][]=$agentinfo[0]['agent_name'];
		// 		$table[$key][]=$agentinfo[0]['agent_qq'];
		// 		$table[$key][]=$agentinfo[0]['mobile'];
		// 		$table[$key][]=$agentinfo[0]['bankname'];
		// 		$table[$key][]=$agentinfo[0]['bankcard'];
		// 		$table[$key][]=$value['money'];
		// 		$table[$key][]=$value['settlementdate'];
		// 		$table[$key][]=$value['addtime'];
		// 	}			
		// }
		// $tablename='GeneralLedger'.$settlementdate.'.xls';
		// $this->exportGeneralLedger($table,$tablename);

		//查询上个月全部已结算分佣记录
		// $sql2="select * from mifi_commission where addtime2 >= $begin and addtime2 < $stop and settlement = 1 order by agent_user_id asc ";
		// $query2 = $this->db->query($sql2);
		// $settlement1=$query2->result_array();
		// if($settlement1){			
		// 	foreach ($settlement1 as $k => $v) {
		// 		$agentinfo=$this->Agent_m->select(array('id'=>$v['agent_user_id']));
		// 		$Everyoneinfo[$k][]=$v['id'];
		// 		$Everyoneinfo[$k][]=$agentinfo[0]['agent_name'];
		// 		$Everyoneinfo[$k][]=$v['device_sn'];
		// 		$Everyoneinfo[$k][]=$v['order_id'];
		// 		$Everyoneinfo[$k][]=$v['flow'];
		// 		$Everyoneinfo[$k][]=$v['money'];
		// 		$Everyoneinfo[$k][]=$v['addtime'];
		// 		$Everyoneinfo[$k][]='已结算';
		// 		$Everyoneinfo[$k][]=$v['settlement_time'];
		// 	}				
		// }
		// $tablename='EveryoneList'.$settlementdate.'.xls';
		// $this->exportEveryoneList($Everyoneinfo,$tablename);

	}

	public function gettime(){
		$firstday=date('Y-m-d', strtotime(date('Y-m-01') . ' -1 month'));
		$begin=date("$firstday 00:00:00");
		$lastday=date('Y-m-01');
		$stop=date("$lastday 00:00:00");
		$data['firstday']=$begin;
		$data['lastday']=$stop;
		echo _echo($data);
		exit;
	}

	//导出某月结算每个代理多少钱的总账
	public function exportGeneralLedger(){
		$settlementdate=date('Ym', strtotime(date('Y-m') . ' -1 month'));
		$datainfo=$this->Settlementlog_m->select(array('settlementdate'=>$settlementdate));
		if($datainfo){
			$i=0;
			foreach ($datainfo as $key => $value) {				
				$agentinfo=$this->Agent_m->select(array('id'=>$value['agent_id']));				
				if($agentinfo[0]['agent_level']==1){
					$data[$i][]=$value['id'];
					$data[$i][]=$agentinfo[0]['agent_name'];
					$data[$i][]="一级代理";
					$data[$i][]=$agentinfo[0]['agent_qq'];
					$data[$i][]=$agentinfo[0]['mobile'];
					$data[$i][]=$agentinfo[0]['bankname'];
					$data[$i][]=$agentinfo[0]['branch'];
					$data[$i][]=$agentinfo[0]['bankcard'];
					$data[$i][]=$value['money'];
					$data[$i][]=$value['settlementdate'];
					$data[$i][]=$value['addtime'];
					$i++;
				}				
			}			
		}
		$name='agent1_tongji'.$settlementdate.'.xls';
		//创建对象  
		$excel = new PHPExcel();  
		//Excel表格式,这里简略写了8列  
		$letter = array('A','B','C','D','E','F','G','H','I','J','K');
		//表头数组  
		$tableheader = array('编号','姓名','代理等级','QQ','手机','银行名称','支行名称','银行卡号码','金额','结算月份','结算时间');
		//填充表头信息  
		for($i = 0;$i < count($tableheader);$i++) {  
		    $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");  
		}  		
		//填充表格信息  
		for ($i = 2;$i <= count($data) + 1;$i++) {  
		    $j = 0;  
		    foreach ($data[$i - 2] as $key=>$value) {  
		        $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");  
		        $j++;  
		    }  
		}  		  
		//创建Excel输入对象  
		$write = new PHPExcel_Writer_Excel5($excel);  
		header("Pragma: public");  
		header("Expires: 0");  
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");  
		header("Content-Type:application/force-download");  
		header("Content-Type:application/vnd.ms-execl");  
		header("Content-Type:application/octet-stream");  
		header("Content-Type:application/download");;  
		header('Content-Disposition:attachment;filename="'.$name.'"');  
		header("Content-Transfer-Encoding:binary");  
		$write->save('php://output');
	}


	//导出每个代理的记录
	public function exportEveryoneList(){
		$firstday=date('Y-m-d', strtotime(date('Y-m-01') . ' -1 month'));
		$begin=strtotime(date("$firstday 00:00:00"));
		$lastday=date('Y-m-01');
		$stop=strtotime(date("$lastday 00:00:00"));
		$settlementdate=date('Ym', strtotime(date('Y-m') . ' -1 month'));
		$sql2="select * from mifi_commission where addtime2 >= $begin and addtime2 < $stop and settlement = 1 order by agent_user_id asc ";
		$query2 = $this->db->query($sql2);
		$settlement1=$query2->result_array();
		if($settlement1){	
			$i=0;
			foreach ($settlement1 as $k => $v) {
				$agentinfo=$this->Agent_m->select(array('id'=>$v['agent_user_id']));
				if($agentinfo[0]['agent_level']==1){
					$data[$i][]=$v['id'];
					$data[$i][]=$agentinfo[0]['agent_name'];
					$data[$i][]='一级代理';
					$data[$i][]=$v['device_sn'];
					$data[$i][]=$v['order_id'];
					$data[$i][]=$v['flow'];
					$data[$i][]=$v['money'];
					$data[$i][]=$v['addtime'];
					$data[$i][]='已结算';
					$data[$i][]=$v['settlement_time'];
					$i++;
				}
			}				
		}
		$name='agent1_list'.$settlementdate.'.xls';
		//创建对象  
		$excel = new PHPExcel();  
		//Excel表格式,这里简略写了8列  
		$letter = array('A','B','C','D','E','F','G','H','I','J');
		//表头数组  
		$tableheader = array('编号','姓名','代理等级','设备编号','订单编号','套餐名称','佣金金额','订单时间','结算状态','结算时间');
		//填充表头信息  
		for($i = 0;$i < count($tableheader);$i++) {  
		    $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");  
		}  		
		//填充表格信息  
		for ($i = 2;$i <= count($data) + 1;$i++) {  
		    $j = 0;  
		    foreach ($data[$i - 2] as $key=>$value) {  
		        $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");  
		        $j++;  
		    }  
		}  		  
		//创建Excel输入对象  
		$write = new PHPExcel_Writer_Excel5($excel);  
		header("Pragma: public");  
		header("Expires: 0");  
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");  
		header("Content-Type:application/force-download");  
		header("Content-Type:application/vnd.ms-execl");  
		header("Content-Type:application/octet-stream");  
		header("Content-Type:application/download");;  
		header('Content-Disposition:attachment;filename="'.$name.'"');  
		header("Content-Transfer-Encoding:binary");  
		$write->save('php://output');		
	}


	//导出某月结算每个代理多少钱的总账
	public function exportTwoGeneralLedger(){
		$settlementdate=date('Ym', strtotime(date('Y-m') . ' -1 month'));
		$datainfo=$this->Settlementlog_m->select(array('settlementdate'=>$settlementdate));
		if($datainfo){
			$i=0;
			foreach ($datainfo as $key => $value) {
				$agentinfo=$this->Agent_m->select(array('id'=>$value['agent_id']));
				if($agentinfo[0]['agent_level']==2){
					$data[$i][]=$value['id'];
					$data[$i][]=$agentinfo[0]['agent_name'];
					$data[$i][]='二级代理';
					$data[$i][]=$agentinfo[0]['agent_qq'];
					$data[$i][]=$agentinfo[0]['mobile'];
					$data[$i][]=$agentinfo[0]['bankname'];
					$data[$i][]=$agentinfo[0]['branch'];
					$data[$i][]=$agentinfo[0]['bankcard'];
					$data[$i][]=$value['money'];
					$data[$i][]=$value['settlementdate'];
					$data[$i][]=$value['addtime'];
					$i++;
				}
			}			
		}
		$name='agent2_tongji'.$settlementdate.'.xls';
		//创建对象  
		$excel = new PHPExcel();  
		//Excel表格式,这里简略写了8列  
		$letter = array('A','B','C','D','E','F','G','H','I','J','K');
		//表头数组  
		$tableheader = array('编号','姓名','代理等级','QQ','手机','银行名称','支行名称','银行卡号码','金额','结算月份','结算时间');
		//填充表头信息  
		for($i = 0;$i < count($tableheader);$i++) {  
		    $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");  
		}  		
		//填充表格信息  
		for ($i = 2;$i <= count($data) + 1;$i++) {  
		    $j = 0;  
		    foreach ($data[$i - 2] as $key=>$value) {  
		        $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");  
		        $j++;  
		    }  
		}  		  
		//创建Excel输入对象  
		$write = new PHPExcel_Writer_Excel5($excel);  
		header("Pragma: public");  
		header("Expires: 0");  
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");  
		header("Content-Type:application/force-download");  
		header("Content-Type:application/vnd.ms-execl");  
		header("Content-Type:application/octet-stream");  
		header("Content-Type:application/download");
		header('Content-Disposition:attachment;filename="'.$name.'"');  
		header("Content-Transfer-Encoding:binary");  
		$write->save('php://output');
	}


	//导出每个代理的记录
	public function exportTwoEveryoneList(){
		$firstday=date('Y-m-d', strtotime(date('Y-m-01') . ' -1 month'));
		$begin=strtotime(date("$firstday 00:00:00"));
		$lastday=date('Y-m-01');
		$stop=strtotime(date("$lastday 00:00:00"));
		$settlementdate=date('Ym', strtotime(date('Y-m') . ' -1 month'));
		$sql2="select * from mifi_commission where addtime2 >= $begin and addtime2 < $stop and settlement = 1 order by agent_user_id asc ";
		
		$query2 = $this->db->query($sql2);
		$settlement1=$query2->result_array();
		if($settlement1){	
			$i=0;
			foreach ($settlement1 as $k => $v) {
				$agentinfo=$this->Agent_m->select(array('id'=>$v['agent_user_id']));
				if($agentinfo[0]['agent_level']==2){
					$data[$i][]=$v['id'];
					$data[$i][]=$agentinfo[0]['agent_name'];
					$data[$i][]='二级代理';
					$data[$i][]=$v['device_sn'];
					$data[$i][]=$v['order_id'];
					$data[$i][]=$v['flow'];
					$data[$i][]=$v['money'];
					$data[$i][]=$v['addtime'];
					$data[$i][]='已结算';
					$data[$i][]=$v['settlement_time'];
					$i++;
				}
			}				
		}
		$name='agent2_list'.$settlementdate.'.xls';
		//创建对象  
		$excel = new PHPExcel();  
		//Excel表格式,这里简略写了8列  
		$letter = array('A','B','C','D','E','F','G','H','I','J');
		//表头数组  
		$tableheader = array('编号','姓名','代理等级','设备编号','订单编号','套餐名称','佣金金额','订单时间','结算状态','结算时间');
		//填充表头信息  
		for($i = 0;$i < count($tableheader);$i++) {  
		    $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");  
		}  		
		//填充表格信息  
		for ($i = 2;$i <= count($data) + 1;$i++) {  
		    $j = 0;  
		    foreach ($data[$i - 2] as $key=>$value) {  
		        $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");  
		        $j++;  
		    }  
		}  		  
		//创建Excel输入对象  
		$write = new PHPExcel_Writer_Excel5($excel);  
		header("Pragma: public");  
		header("Expires: 0");  
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");  
		header("Content-Type:application/force-download");  
		header("Content-Type:application/vnd.ms-execl");  
		header("Content-Type:application/octet-stream");  
		header("Content-Type:application/download");
		header('Content-Disposition:attachment;filename="'.$name.'"');  
		header("Content-Transfer-Encoding:binary");  
		$write->save('php://output');		
	}

	//获取上次登录的收据
	public function adminLogs(){
		$sql=$this->db->query("select log_ip,log_time,admin_id from mifi_admin_log order by log_id desc limit 1,1");
    	$admin_log=$sql->result_array();
    	$admin = $this->Admin_m->get_one(array('admin_id'=>$admin_log[0]['admin_id']));
    	$data['admin'] = $admin['username'];
    	$data['log_ip'] = $admin_log[0]['log_ip'];
    	$data['log_time'] = date('Y-m-d H:i:s',$admin_log[0]['log_time']);
    	echo _echo($data);exit;
	}
	
    //总后台登录
    public function adminlogin(){
        $where['username'] = $this->input->post('username');
        $where['password'] = md5($this->input->post('password'));

        if(empty($where['username'])||empty($where['password'])){
            $data['success'] = error('4008');
            echo _echo($data);
            exit;
        }
        $result=$this->adminapi_service->getAdminByNicknameAndPassword($where);
        if ($result['success']['code'] == 4000) {
        	// $_SESSION['admin']['admin_id']
        	echo _echo($result['admin_id']);exit;
        }
    }
    //判断是否登录
    public function loginRequest(){
    	if (empty($_SESSION['admin']['admin_id'])) {
    		echo json_encode(['code'=>0,'codes'=>0,'infomsg'=>"还未登录"]);
           	exit;
    	}else{
    		echo json_encode(['code'=>1,'codes'=>0,'infomsg'=>"已经登录"]);
           	exit;
    	}
    }
    //退出登录
    public function loginoutcenter(){
    	unset($_SESSION['admin']);
    	echo _echo(1);exit;//退出成功
    }
    //判断是否带正确的登录参数
    public function islogin(){
        $tooken = $this->input->get('tooken');
        //没接收到参数
        if(empty($tooken)){
            $data['success'] = error('4008');
            echo _echo($data);
            exit;
        }else{
            //解密解不出来
            $adminid=jiemi($tooken);
            if(empty($adminid)){
                $data['success'] = error('4008');
                echo _echo($data);
                exit;
            }
            //没有查到该管理员
            $admin=$this->Admin_m->select(array('admin_id'=>$adminid));
            if(empty($admin)){
                $data['success'] = error('4008');
                echo _echo($data);
                exit;
            }
            return $admin;
        }
    }


    /**
     * 首页概览
     * @param tooken        登录通行证
     */
    public function index(){
    	//$admin=$this->islogin();
    	$admin=$this->Admin_m->select(array('admin_id'=>1));
    	//查该管理员最后一次登录时间和IP
    	$adminlog=$this->Adminlog_m->select(array('admin_id'=>$admin[0]['admin_id'],'log_info'=>'管理员登录'),'log_id desc',2);
    	if(count($adminlog,0)==2){
    		$admin[0]['log_ip']=$adminlog[1]['log_ip'];
    		$admin[0]['log_time']=$adminlog[1]['log_time'];
    	}else{
    		$admin[0]['log_ip']=$adminlog[0]['log_ip'];
    		$admin[0]['log_time']=$adminlog[0]['log_time'];
    	}
    	//查代理数量
    	$query=$this->db->query('select count(id) as num from mifi_agent ');
    	$agent=$query->result_array();
    	$query=$this->db->query('select count(id) as num from mifi_agent where agent_level = 1 ');
    	$agent1=$query->result_array();
    	$query=$this->db->query('select count(id) as num from mifi_agent where agent_level = 2 ');
    	$agent2=$query->result_array();
    	//查会员数量
    	$query=$this->db->query('select count(user_id) as num from mifi_users ');
    	$users=$query->result_array();
    	//订单数量
    	$query=$this->db->query('select count(orderid) as num from mifi_order where paystate = 1 ');
    	$ordernum=$query->result_array();
    	//最近两周订单数量
    	//获取当天的日期 本周前几天的数据 上周七天的数据
    	
    	//设备数量
    	$query=$this->db->query('select count(device_id) as num from mifi_device ');
    	$devicenum=$query->result_array();
    	//最近两周设备数量
    	//获取当天的日期 本周前几天的数据 上周七天的数据
    	
    	//最近两月订单数量
    	//最近一月设备激活情况

    	$data['success'] = success();
    	$data['admin'] = $admin[0];
    	$data['agentnum']['all'] = $agent[0]['num'];
    	$data['agentnum']['agent1'] = $agent1[0]['num'];
    	$data['agentnum']['agent2'] = $agent2[0]['num'];
    	$data['usernum'] = $users[0]['num'];
    	$data['ordernum'] = $ordernum[0]['num'];
    	$data['devicenum'] = $devicenum[0]['num'];
        echo _echo($data);
        exit;
    }


    /**
     * 修改系統設置
     * @param tooken        登录通行证
     */
    public function setadminsetting(){
        $admin=$this->islogin();
        $data=$this->input->post();
        if(isset($data['inc_type'])){
        	$data['success'] = error('4008');
            echo _echo($data);
            exit;
        }
        foreach ($data as $key => $value) {
        	if($key=='inc_type'){
        	}else{
        		$this->Config_m->update(array('inc_type'=>$data['inc_type'],'name'=>$key),array('value'=>$value));
        	}
        }

        //系统设置日志
		$log['admin_id']=$admin[0]['admin_id'];
		$log['log_info']='系统设置'.json_encode($data);
		$log['log_ip']=$_SERVER["REMOTE_ADDR"];
		$log['log_time']=time();
    	$this->CI->Adminlog_m->insert($log);

    	$return['success'] = success();
        echo _echo($return);
        exit;
    }

    /**
     * 查看系統設置
     * @param tooken        登录通行证
     */
    public function getadminsetting(){
        $admin=$this->islogin();
        $inc_type=$this->input->get('inc_type');
        if($inc_type){
        	$data['success'] = error('4008');
            echo _echo($data);
            exit;
        }
        $data=$this->Config_m->select(array('inc_type'=>$data['inc_type']));
        $return['inc_type']=$inc_type;
        if($data){
        	foreach ($data as $key => $value) {
	        	$return[$value['name']]=$value['value'];
	        }
        }
    	$return['success'] = success();
        echo _echo($return);
        exit;
    }


    









    





}


